﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Citi.EmailSender.Domain;
using Citi.EmailSender.WebUi.Models;
using Citi.Helpers;

namespace Citi.EmailSender.WebUi.Controllers
{
    public class TemplateController : ControllerBase
    {
       
        public ActionResult Index()
        {
            var emailSenderUrl = string.Format("{0}://{1}{2}{3}/", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"), "Templates");
            var templates = new EmailData().SelectTemplates();
            templates.ForEach(x => x.Url = !string.IsNullOrWhiteSpace(x.Url) && !x.Url.StartsWith("http") ? string.Concat(emailSenderUrl, x.Url) : x.Url);
            return View(new EmailDataModel().CreateModel(templates));
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(EmailDataModel model, string parameters, HttpPostedFileBase uploadHtml)
        {
            var domain = model.CreateDomain();
            domain.ApplicationKey = Guid.NewGuid().ToString();
            domain.Active = true;
            domain.Template = true;

            foreach (var parameter in parameters.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                domain.EmailDataParameters.Add(new EmailDataParameter { Name = parameter });

            domain.Save(domain);

            if (uploadHtml != null)
            {
                var fileName = string.Concat(domain.Id, Path.GetExtension(uploadHtml.FileName));
                uploadHtml.SaveAs(Path.Combine(Server.MapPath(Url.Content("~/Templates")), fileName));
                domain.Url = fileName;
                domain.Save(domain);
            }

            return RedirectToAction("Index");
        }

        public ActionResult Create()
        {
            FillViewBags();
            return View();
        }

        private void FillViewBags(int? applicationId = null, int? onBehalfOfId = null)
        {
            ViewBag.Applications = new Application().SelectAllActive<Application>().OrderBy(x => x.FullName)
                                                .ToSelectList(x => x.FullName, x => x.Id.ToString(), applicationId.HasValue ? applicationId.Value.ToString() : null);

            ViewBag.OnBehalfOfs = new OnBehalfOf().SelectAllActive<OnBehalfOf>().OrderBy(x => x.FriendlyName)
                                                  .ToSelectList(x => x.FriendlyName, x => x.Id.ToString(), onBehalfOfId.HasValue ? onBehalfOfId.Value.ToString() : null);

            ViewBag.Importances = new List<SelectListItem>
                {
                    new SelectListItem{Text = Enums.EmailImportance.Low.GetDescription(),Value = ((int) Enums.EmailImportance.Low).ToString()},
                    new SelectListItem{Text = Enums.EmailImportance.Normal.GetDescription(),Value = ((int) Enums.EmailImportance.Normal).ToString()},
                    new SelectListItem{Text = Enums.EmailImportance.High.GetDescription(),Value = ((int) Enums.EmailImportance.High).ToString()}
                };
        }

        public ActionResult Preview(int id)
        {
            var model = new EmailDataModel().CreateModel(new EmailData().SelectById<EmailData>(id));

            if (string.IsNullOrWhiteSpace(model.Body))
            {
                var emailSenderUrl = string.Format("{0}://{1}{2}{3}/", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"), "Templates");
                model.Url = !model.Url.StartsWith("http") ? string.Concat(emailSenderUrl, model.Url) : model.Url;
                model.Body = EmailHelper.GetEmailBody(model.Url, NetworkUser, NetWorkPassword, NetworkDomain, Proxy);
            }

            return PartialView(model);
        }
    }
}
